package com.google.bitcoin.db;

import com.amazonaws.services.dynamodb.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodb.model.*;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.AmazonClientException;


public class DynamoRateLimited extends AmazonDynamoDBClient
{
    private double read_limit;
    private volatile long next_read_allowed;

    public DynamoRateLimited(AWSCredentials awsCredentials, double read_limit)
    {
        super(awsCredentials);
        this.read_limit = read_limit;
    }

    public ScanResult scan(ScanRequest scanRequest)
        throws AmazonServiceException, AmazonClientException
    {
        privateReadDelay();

        ScanResult res = super.scan(scanRequest);
        updateReadDelay(res.getConsumedCapacityUnits());
        return res;
    }

    private void privateReadDelay()
    {
        while(System.currentTimeMillis() < next_read_allowed)
        {
            try
            {
                Thread.sleep(next_read_allowed - System.currentTimeMillis());
            }
            catch(java.lang.InterruptedException e)
            {}
        }
    }
    private synchronized void updateReadDelay(double used)
    {
        long taken = (long)(used / (read_limit / 1000.0));

        long start = Math.max(System.currentTimeMillis(), next_read_allowed);
        next_read_allowed = start + taken;
    }
    
    
}
